[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, isClient, isIPageInfoForEntity, IUser, IUserHasId, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import ExtensibleCustomError from 'extensible-custom-error';
  7. import { model as mongooseModel } from 'mongoose';
  8. import {
  9. NextPage, GetServerSideProps, GetServerSidePropsContext,
  10. } from 'next';
  11. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  12. import dynamic from 'next/dynamic';
  13. import Head from 'next/head';
  14. import { useRouter } from 'next/router';
  15. import superjson from 'superjson';
  16. import { Comments } from '~/components/Comments';
  17. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  18. // import { useTranslation } from '~/i18n';
  19. import { PageContentFooter } from '~/components/PageContentFooter';
  20. import { CrowiRequest } from '~/interfaces/crowi-request';
  21. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  22. // import { useIndentSize } from '~/stores/editor';
  23. // import { useRendererSettings } from '~/stores/renderer';
  24. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  25. import { EditorConfig } from '~/interfaces/editor-settings';
  26. import { CustomWindow } from '~/interfaces/global';
  27. import { RendererConfig } from '~/interfaces/services/renderer';
  28. import { ISidebarConfig } from '~/interfaces/sidebar-config';
  29. import { IUserUISettings } from '~/interfaces/user-ui-settings';
  30. import { PageModel, PageDocument } from '~/server/models/page';
  31. import { PageRedirectModel } from '~/server/models/page-redirect';
  32. import { UserUISettingsModel } from '~/server/models/user-ui-settings';
  33. import { useSWRxCurrentPage, useSWRxIsGrantNormalized } from '~/stores/page';
  34. import { useRedirectFrom } from '~/stores/page-redirect';
  35. import {
  36. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth, useSelectedGrant,
  37. } from '~/stores/ui';
  38. import loggerFactory from '~/utils/logger';
  39. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  40. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  41. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  42. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  43. import { BasicLayout } from '../components/Layout/BasicLayout';
  44. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  45. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  46. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  47. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  48. import {
  49. useCurrentUser, useCurrentPagePath,
  50. useIsLatestRevision,
  51. useIsForbidden, useIsNotFound, useIsTrashPage, useIsSharedUser,
  52. useIsEnabledStaleNotification, useIsIdenticalPath,
  53. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  54. useHackmdUri,
  55. useIsAclEnabled, useIsUserPage, useIsNotCreatable,
  56. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  57. useIsSlackConfigured, useRendererConfig, useEditingMarkdown,
  58. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage,
  59. } from '../stores/context';
  60. import {
  61. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  62. } from './utils/commons';
  63. // import { useCurrentPageSWR } from '../stores/page';
  64. import styles from './[[...path]].page.module.scss';
  65. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  66. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  67. const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
  68. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  69. const logger = loggerFactory('growi:pages:all');
  70. const {
  71. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage,
  72. } = pagePathUtils;
  73. const { removeHeadingSlash } = pathUtils;
  74. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  75. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  76. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  77. {
  78. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  79. return v?.data != null
  80. && v?.data.toObject != null
  81. && v?.meta != null
  82. && isIPageInfoForEntity(v.meta);
  83. },
  84. serialize: (v) => {
  85. return {
  86. data: superjson.stringify(v.data.toObject()),
  87. meta: superjson.stringify(v.meta),
  88. };
  89. },
  90. deserialize: (v) => {
  91. return {
  92. data: superjson.parse(v.data),
  93. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  94. };
  95. },
  96. },
  97. 'IPageToShowRevisionWithMetaTransformer',
  98. );
  99. const IdenticalPathPage = (): JSX.Element => {
  100. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  101. return <IdenticalPathPage />;
  102. };
  103. const PutbackPageModal = (): JSX.Element => {
  104. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  105. return <PutbackPageModal />;
  106. };
  107. type Props = CommonProps & {
  108. currentUser: IUser,
  109. pageWithMeta: IPageToShowRevisionWithMeta,
  110. // pageUser?: any,
  111. redirectFrom?: string;
  112. // shareLinkId?: string;
  113. isLatestRevision?: boolean
  114. isIdenticalPathPage?: boolean,
  115. isForbidden: boolean,
  116. isNotFound: boolean,
  117. IsNotCreatable: boolean,
  118. // isAbleToDeleteCompletely: boolean,
  119. isSearchServiceConfigured: boolean,
  120. isSearchServiceReachable: boolean,
  121. isSearchScopeChildrenAsDefault: boolean,
  122. isSlackConfigured: boolean,
  123. // isMailerSetup: boolean,
  124. isAclEnabled: boolean,
  125. // hasSlackConfig: boolean,
  126. // drawioUri: string,
  127. hackmdUri: string,
  128. // noCdn: string,
  129. // highlightJsStyle: string,
  130. isAllReplyShown: boolean,
  131. // isContainerFluid: boolean,
  132. editorConfig: EditorConfig,
  133. isEnabledStaleNotification: boolean,
  134. // isEnabledLinebreaks: boolean,
  135. // isEnabledLinebreaksInComments: boolean,
  136. // adminPreferredIndentSize: number,
  137. // isIndentSizeForced: boolean,
  138. disableLinkSharing: boolean,
  139. rendererConfig: RendererConfig,
  140. // UI
  141. userUISettings?: IUserUISettings
  142. // Sidebar
  143. sidebarConfig: ISidebarConfig,
  144. };
  145. const GrowiPage: NextPage<Props> = (props: Props) => {
  146. // const { t } = useTranslation();
  147. const router = useRouter();
  148. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  149. // register global EventEmitter
  150. if (isClient()) {
  151. (window as CustomWindow).globalEmitter = new EventEmitter();
  152. }
  153. // commons
  154. useEditorConfig(props.editorConfig);
  155. useCsrfToken(props.csrfToken);
  156. // UserUISettings
  157. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  158. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  159. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  160. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  161. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  162. // page
  163. useIsLatestRevision(props.isLatestRevision);
  164. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  165. useIsForbidden(props.isForbidden);
  166. useIsNotFound(props.isNotFound);
  167. useIsNotCreatable(props.IsNotCreatable);
  168. useRedirectFrom(props.redirectFrom);
  169. // useIsTrashPage(_isTrashPage(props.currentPagePath));
  170. // useShared();
  171. // useShareLinkId(props.shareLinkId);
  172. useIsSharedUser(false); // this page cann't be routed for '/share'
  173. useIsIdenticalPath(false); // TODO: need to initialize from props
  174. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  175. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  176. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  177. useIsSearchServiceReachable(props.isSearchServiceReachable);
  178. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  179. useIsSlackConfigured(props.isSlackConfigured);
  180. // useIsMailerSetup(props.isMailerSetup);
  181. useIsAclEnabled(props.isAclEnabled);
  182. // useHasSlackConfig(props.hasSlackConfig);
  183. // useDrawioUri(props.drawioUri);
  184. useHackmdUri(props.hackmdUri);
  185. // useNoCdn(props.noCdn);
  186. // useIndentSize(props.adminPreferredIndentSize);
  187. useDisableLinkSharing(props.disableLinkSharing);
  188. useRendererConfig(props.rendererConfig);
  189. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  190. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  191. useIsAllReplyShown(props.isAllReplyShown);
  192. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  193. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  194. // const { data: editorMode } = useEditorMode();
  195. const { pageWithMeta, userUISettings } = props;
  196. let shouldRenderPutbackPageModal = false;
  197. if (pageWithMeta != null) {
  198. shouldRenderPutbackPageModal = _isTrashPage(pageWithMeta.data.path);
  199. }
  200. const pageId = pageWithMeta?.data._id;
  201. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  202. useCurrentPageId(pageId);
  203. useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
  204. useIsTrashPage(_isTrashPage(pagePath));
  205. useIsUserPage(isUserPage(pagePath));
  206. useIsNotCreatable(props.isForbidden || !isCreatablePage(pagePath)); // TODO: need to include props.isIdentical
  207. useCurrentPagePath(pagePath);
  208. useCurrentPathname(props.currentPathname);
  209. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  210. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  211. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  212. // sync grant data
  213. useEffect(() => {
  214. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  215. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  216. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  217. useEffect(() => {
  218. const decodedURI = decodeURI(window.location.pathname);
  219. if (isClient() && decodedURI !== props.currentPathname) {
  220. router.replace(props.currentPathname, undefined, { shallow: true });
  221. }
  222. }, [props.currentPathname, router]);
  223. const classNames: string[] = [];
  224. // switch (editorMode) {
  225. // case EditorMode.Editor:
  226. // classNames.push('on-edit', 'builtin-editor');
  227. // break;
  228. // case EditorMode.HackMD:
  229. // classNames.push('on-edit', 'hackmd');
  230. // break;
  231. // }
  232. // if (page == null) {
  233. // classNames.push('not-found-page');
  234. // }
  235. return (
  236. <>
  237. <Head>
  238. {/*
  239. {renderScriptTagByName('drawio-viewer')}
  240. {renderScriptTagByName('highlight-addons')}
  241. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  242. */}
  243. </Head>
  244. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  245. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')} expandContainer={props.isContainerFluid}>
  246. <div className="h-100 d-flex flex-column justify-content-between">
  247. <header className="py-0 position-relative">
  248. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  249. </header>
  250. <div className="d-edit-none">
  251. <GrowiSubNavigationSwitcher />
  252. </div>
  253. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  254. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  255. <div className="flex-grow-1">
  256. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  257. <div id="content-main" className="content-main grw-container-convertible">
  258. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  259. { !props.isIdenticalPathPage && (
  260. <>
  261. <PageAlerts />
  262. { props.isForbidden && <ForbiddenPage /> }
  263. { props.IsNotCreatable && <NotCreatablePage />}
  264. { !props.isForbidden && !props.IsNotCreatable && <DisplaySwitcher />}
  265. {/* <DisplaySwitcher /> */}
  266. {/* <PageStatusAlert /> */}
  267. </>
  268. ) }
  269. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  270. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  271. <div id="revision-toc-content" className="revision-toc-content"></div>
  272. </div>
  273. </div> */}
  274. </div>
  275. </div>
  276. </div>
  277. {/* TODO: Check CSS import */}
  278. <footer className="footer d-edit-none">
  279. {/* TODO: Enable page_list.html */}
  280. {/* TODO: Enable isIdenticalPathPage or useIdenticalPath */}
  281. {/* { !props.isIdenticalPathPage && ( */}
  282. <Comments pageId={pageId} />
  283. {/* )} */}
  284. {/* TODO: Create UsersHomePageFooter conponent */}
  285. { isUsersHomePage(props.currentPathname) && (
  286. <div className="container-lg user-page-footer py-5">
  287. <div className="grw-user-page-list-m d-edit-none">
  288. <h2 id="bookmarks-list" className="grw-user-page-header border-bottom pb-2 mb-3">
  289. <i style={{ fontSize: '1.3em' }} className="fa fa-fw fa-bookmark-o"></i>
  290. Bookmarks
  291. </h2>
  292. <div id="user-bookmark-list" className={`page-list ${styles['page-list']}`}>
  293. {/* TODO: No need page-list-container class ? */}
  294. <div className="page-list-container">
  295. {/* <BookmarkList userId={pageContainer.state.creator._id} /> */}
  296. </div>
  297. </div>
  298. </div>
  299. <div className="grw-user-page-list-m mt-5 d-edit-none">
  300. <h2 id="recently-created-list" className="grw-user-page-header border-bottom pb-2 mb-3">
  301. <i id="recent-created-icon" className="mr-1">
  302. {/* <RecentlyCreatedIcon /> */}
  303. </i>
  304. Recently Created
  305. </h2>
  306. <div id="user-created-list" className={`page-list ${styles['page-list']}`}>
  307. {/* TODO: No need page-list-container class ? */}
  308. <div className="page-list-container">
  309. {/* <RecentCreated userId={pageContainer.state.creator._id} /> */}
  310. </div>
  311. </div>
  312. </div>
  313. </div>
  314. )}
  315. <PageContentFooter />
  316. </footer>
  317. <UnsavedAlertDialog />
  318. <DescendantsPageListModal />
  319. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  320. </div>
  321. </BasicLayout>
  322. </>
  323. );
  324. };
  325. function getPageIdFromPathname(currentPathname: string): string | null {
  326. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  327. }
  328. class MultiplePagesHitsError extends ExtensibleCustomError {
  329. pagePath: string;
  330. constructor(pagePath: string) {
  331. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  332. this.pagePath = pagePath;
  333. }
  334. }
  335. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  336. const req: CrowiRequest = context.req as CrowiRequest;
  337. const { crowi } = req;
  338. const { revisionId } = req.query;
  339. const Page = crowi.model('Page') as PageModel;
  340. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  341. const { pageService } = crowi;
  342. let currentPathname = props.currentPathname;
  343. const pageId = getPageIdFromPathname(currentPathname);
  344. const isPermalink = _isPermalink(currentPathname);
  345. const { user } = req;
  346. if (!isPermalink) {
  347. // check redirects
  348. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  349. if (chains != null) {
  350. // overwrite currentPathname
  351. currentPathname = chains.end.toPath;
  352. props.currentPathname = currentPathname;
  353. // set redirectFrom
  354. props.redirectFrom = chains.start.fromPath;
  355. }
  356. // check whether the specified page path hits to multiple pages
  357. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  358. if (count > 1) {
  359. throw new MultiplePagesHitsError(currentPathname);
  360. }
  361. }
  362. const pageWithMeta: IPageToShowRevisionWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  363. const page = pageWithMeta?.data as unknown as PageDocument;
  364. // populate & check if the revision is latest
  365. if (page != null) {
  366. page.initLatestRevisionField(revisionId);
  367. await page.populateDataToShowRevision();
  368. props.isLatestRevision = page.isLatestRevision();
  369. }
  370. props.pageWithMeta = pageWithMeta;
  371. }
  372. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  373. const req = context.req as CrowiRequest<IUserHasId & any>;
  374. const { user } = req;
  375. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  376. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  377. if (userUISettings != null) {
  378. props.userUISettings = userUISettings.toObject();
  379. }
  380. }
  381. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  382. const req: CrowiRequest = context.req as CrowiRequest;
  383. const { crowi } = req;
  384. const Page = crowi.model('Page') as PageModel;
  385. const { currentPathname } = props;
  386. const pageId = getPageIdFromPathname(currentPathname);
  387. const isPermalink = _isPermalink(currentPathname);
  388. const page = props.pageWithMeta?.data;
  389. if (props.isIdenticalPathPage) {
  390. // TBD
  391. }
  392. else if (page == null) {
  393. props.isNotFound = true;
  394. props.IsNotCreatable = !isCreatablePage(currentPathname);
  395. // check the page is forbidden or just does not exist.
  396. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  397. props.isForbidden = count > 0;
  398. }
  399. else {
  400. props.isNotFound = page.isEmpty;
  401. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  402. if (isPermalink && page.isEmpty) {
  403. props.currentPathname = page.path;
  404. }
  405. // /path/to/page ==> /62a88db47fed8b2d94f30000
  406. if (!isPermalink && !page.isEmpty) {
  407. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  408. if (!isToppage) {
  409. props.currentPathname = `/${page._id}`;
  410. }
  411. }
  412. }
  413. }
  414. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  415. // const req: CrowiRequest = context.req as CrowiRequest;
  416. // const { crowi } = req;
  417. // const UserModel = crowi.model('User');
  418. // if (isUserPage(props.currentPagePath)) {
  419. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  420. // if (user != null) {
  421. // props.pageUser = JSON.stringify(user.toObject());
  422. // }
  423. // }
  424. // }
  425. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  426. const req: CrowiRequest = context.req as CrowiRequest;
  427. const { crowi } = req;
  428. const {
  429. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  430. } = crowi;
  431. props.isSearchServiceConfigured = searchService.isConfigured;
  432. props.isSearchServiceReachable = searchService.isReachable;
  433. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  434. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  435. // props.isMailerSetup = mailService.isMailerSetup;
  436. props.isAclEnabled = aclService.isAclEnabled();
  437. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  438. // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  439. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  440. // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  441. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  442. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  443. // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  444. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  445. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  446. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  447. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  448. props.editorConfig = {
  449. upload: {
  450. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  451. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  452. },
  453. };
  454. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  455. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  456. props.rendererConfig = {
  457. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  458. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  459. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  460. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  461. plantumlUri: process.env.PLANTUML_URI ?? null,
  462. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  463. // XSS Options
  464. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  465. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  466. tagWhiteList: crowi.xssService.getTagWhiteList(),
  467. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  468. };
  469. props.sidebarConfig = {
  470. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  471. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  472. };
  473. }
  474. /**
  475. * for Server Side Translations
  476. * @param context
  477. * @param props
  478. * @param namespacesRequired
  479. */
  480. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  481. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  482. props._nextI18Next = nextI18NextConfig._nextI18Next;
  483. }
  484. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  485. const req = context.req as CrowiRequest<IUserHasId & any>;
  486. const { user } = req;
  487. const result = await getServerSideCommonProps(context);
  488. // check for presence
  489. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  490. if (!('props' in result)) {
  491. throw new Error('invalid getSSP result');
  492. }
  493. const props: Props = result.props as Props;
  494. if (props.redirectDestination != null) {
  495. return {
  496. redirect: {
  497. permanent: false,
  498. destination: props.redirectDestination,
  499. },
  500. };
  501. }
  502. if (user != null) {
  503. props.currentUser = user.toObject();
  504. }
  505. try {
  506. await injectPageData(context, props);
  507. }
  508. catch (err) {
  509. if (err instanceof MultiplePagesHitsError) {
  510. props.isIdenticalPathPage = true;
  511. }
  512. else {
  513. throw err;
  514. }
  515. }
  516. await injectUserUISettings(context, props);
  517. await injectRoutingInformation(context, props);
  518. injectServerConfigurations(context, props);
  519. await injectNextI18NextConfigurations(context, props, ['translation']);
  520. return {
  521. props,
  522. };
  523. };
  524. export default GrowiPage;